import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Dialogs 1.3

/**
 * 报警记录页
 * 支持查询、过滤、确认和导出报警记录
 * 
 * 布局优化：最大化表格数据显示区域
 * - 可用区域：约794px宽 × 738px高（1024-200-30 × 768-30）
 * - 标题栏：40px（压缩）
 * - 查询面板：100px（压缩，单行布局）
 * - 数据列表：剩余空间（约598px）- 最大化显示
 */
Item {
    id: root

    // 查询参数
    property int selectedMeterId: -1  // -1表示所有电表
    property int selectedAlarmType: 0 // 0=全部, 1=电压, 2=电流, 3=离线
    property int acknowledgedFilter: -1 // -1=全部, 0=未确认, 1=已确认
    property var startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) // 默认最近7天
    property var endDate: new Date()
    property bool isQuerying: false
    
    // 分页参数
    property int pageSize: 50  // 每页50条
    property int currentPage: 1  // 当前页码（从1开始）
    property int totalPages: 0  // 总页数
    
    // 统计信息
    property var statistics: ({
        totalCount: 0,
        unacknowledgedCount: 0,
        voltageCount: 0,
        currentCount: 0,
        offlineCount: 0
    })
    
    // 选中的报警ID列表（用于批量确认）
    property var selectedAlarmIds: []

    ColumnLayout {
        anchors.fill: parent
        spacing: 8

        // 页面标题和统计（压缩到40px）
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 40
            Layout.minimumHeight: 40
            Layout.maximumHeight: 40
            color: "white"
            radius: 6

            RowLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 15

                Text {
                    text: "⚠️ 报警记录查询"
                    font.pixelSize: 16
                    font.bold: true
                    color: "#2c3e50"
                }

                Rectangle {
                    width: 1
                    height: 20
                    color: "#d0d0d0"
                }

                // 总计
                Row {
                    spacing: 5
                    Text {
                        text: "总计:"
                        font.pixelSize: 10
                        color: "#7f8c8d"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    Text {
                        text: root.statistics.totalCount
                        font.pixelSize: 13
                        font.bold: true
                        color: "#2c3e50"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                }

                Rectangle {
                    width: 1
                    height: 20
                    color: "#d0d0d0"
                }

                // 未确认
                Row {
                    spacing: 5
                    Text {
                        text: "未确认:"
                        font.pixelSize: 10
                        color: "#7f8c8d"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    Text {
                        text: root.statistics.unacknowledgedCount
                        font.pixelSize: 13
                        font.bold: true
                        color: "#e74c3c"
                        anchors.verticalCenter: parent.verticalCenter
                        
                        SequentialAnimation on opacity {
                            running: root.statistics.unacknowledgedCount > 0
                            loops: Animation.Infinite
                            NumberAnimation { to: 0.3; duration: 800 }
                            NumberAnimation { to: 1.0; duration: 800 }
                        }
                    }
                }

                Rectangle {
                    width: 1
                    height: 20
                    color: "#d0d0d0"
                }

                // 电压报警
                Row {
                    spacing: 4
                    Rectangle {
                        width: 8
                        height: 8
                        radius: 1
                        color: "#e74c3c"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    Text {
                        text: "电压:" + root.statistics.voltageCount
                        font.pixelSize: 10
                        color: "#2c3e50"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                }

                // 电流报警
                Row {
                    spacing: 4
                    Rectangle {
                        width: 8
                        height: 8
                        radius: 1
                        color: "#f39c12"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    Text {
                        text: "电流:" + root.statistics.currentCount
                        font.pixelSize: 10
                        color: "#2c3e50"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                }

                // 离线报警
                Row {
                    spacing: 4
                    Rectangle {
                        width: 8
                        height: 8
                        radius: 1
                        color: "#95a5a6"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    Text {
                        text: "离线:" + root.statistics.offlineCount
                        font.pixelSize: 10
                        color: "#2c3e50"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                }

                Item {
                    Layout.fillWidth: true
                }
            }
        }

        // 查询条件面板（压缩到100px，单行紧凑布局）
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 100
            Layout.minimumHeight: 100
            Layout.maximumHeight: 100
            color: "white"
            radius: 6

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 6

                Text {
                    text: "🔍 查询条件"
                    font.pixelSize: 12
                    font.bold: true
                    color: "#2c3e50"
                }

                // 第一行：电表、类型、开始时间、结束时间
                Row {
                    spacing: 10

                    Text {
                        text: "电表:"
                        font.pixelSize: 10
                        color: "#2c3e50"
                        anchors.verticalCenter: parent.verticalCenter
                    }

                    ComboBox {
                        id: meterCombo
                        width: 100
                        height: 26
                        font.pixelSize: 10
                        model: ["全部", "配电室A", "配电室B", "配电室C"]
                        
                        onCurrentIndexChanged: {
                            switch(currentIndex) {
                                case 0: root.selectedMeterId = -1; break
                                case 1: root.selectedMeterId = 1; break
                                case 2: root.selectedMeterId = 41; break
                                case 3: root.selectedMeterId = 81; break
                            }
                        }
                    }

                    Text {
                        text: "类型:"
                        font.pixelSize: 10
                        color: "#2c3e50"
                        anchors.verticalCenter: parent.verticalCenter
                    }

                    ComboBox {
                        id: alarmTypeCombo
                        width: 100
                        height: 26
                        font.pixelSize: 10
                        model: ["全部", "电压", "电流", "离线"]
                        
                        onCurrentIndexChanged: {
                            root.selectedAlarmType = currentIndex
                        }
                    }

                    Text {
                        text: "开始:"
                        font.pixelSize: 10
                        color: "#2c3e50"
                        anchors.verticalCenter: parent.verticalCenter
                    }

                    TextField {
                        id: startTimeField
                        width: 130
                        height: 26
                        font.pixelSize: 9
                        text: Qt.formatDateTime(root.startDate, "yyyy-MM-dd HH:mm")
                        readOnly: true
                    }

                    Text {
                        text: "结束:"
                        font.pixelSize: 10
                        color: "#2c3e50"
                        anchors.verticalCenter: parent.verticalCenter
                    }

                    TextField {
                        id: endTimeField
                        width: 130
                        height: 26
                        font.pixelSize: 9
                        text: Qt.formatDateTime(root.endDate, "yyyy-MM-dd HH:mm")
                        readOnly: true
                    }
                }

                // 第二行：状态选择 + 操作按钮
                Row {
                    spacing: 8

                    Text {
                        text: "状态:"
                        font.pixelSize: 10
                        color: "#2c3e50"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    
                    RadioButton {
                        id: ackAll
                        text: "全部"
                        font.pixelSize: 9
                        checked: true
                        height: 26
                        onCheckedChanged: if (checked) root.acknowledgedFilter = -1
                    }
                    
                    RadioButton {
                        id: ackUnconfirmed
                        text: "未确认"
                        font.pixelSize: 9
                        height: 26
                        onCheckedChanged: if (checked) root.acknowledgedFilter = 0
                    }
                    
                    RadioButton {
                        id: ackConfirmed
                        text: "已确认"
                        font.pixelSize: 9
                        height: 26
                        onCheckedChanged: if (checked) root.acknowledgedFilter = 1
                    }

                    Item { width: 15 }

                    Button {
                        text: "🔍 查询"
                        font.pixelSize: 10
                        font.bold: true
                        implicitHeight: 26
                        implicitWidth: 70
                        enabled: !root.isQuerying
                        onClicked: queryAlarms()
                    }

                    Button {
                        text: "📥 CSV"
                        font.pixelSize: 10
                        implicitHeight: 26
                        implicitWidth: 65
                        onClicked: saveDialog.open()
                    }

                    Button {
                        text: "🔄"
                        font.pixelSize: 10
                        implicitHeight: 26
                        implicitWidth: 35
                        onClicked: queryAlarms()
                    }
                }
            }
        }

        // 数据列表（最大化，自动填充剩余空间）
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "white"
            radius: 6

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 6

                // 表头和批量操作（压缩到28px）
                RowLayout {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 28
                    Layout.minimumHeight: 28
                    spacing: 8

                    CheckBox {
                        id: selectAllCheckbox
                        text: "全选"
                        font.pixelSize: 9
                        height: 24
                        onCheckedChanged: {
                            if (checked) {
                                selectAllAlarms()
                            } else {
                                root.selectedAlarmIds = []
                            }
                        }
                    }

                    Button {
                        text: "批量确认"
                        font.pixelSize: 9
                        implicitHeight: 24
                        implicitWidth: 65
                        enabled: root.selectedAlarmIds.length > 0
                        onClicked: batchAcknowledge()
                    }

                    Button {
                        text: "全部确认"
                        font.pixelSize: 9
                        implicitHeight: 24
                        implicitWidth: 65
                        onClicked: acknowledgeAll()
                    }

                    Item { Layout.fillWidth: true }

                    Text {
                        text: "已选 " + root.selectedAlarmIds.length + " 条"
                        font.pixelSize: 9
                        color: "#7f8c8d"
                    }
                }

                // 表头（压缩到30px）
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 30
                    Layout.minimumHeight: 30
                    Layout.maximumHeight: 30
                    color: "#ecf0f1"
                    radius: 3

                    Row {
                        anchors.fill: parent
                        anchors.leftMargin: 8
                        anchors.rightMargin: 8
                        spacing: 0

                        HeaderCell { text: "☑"; widthRatio: 0.05 }
                        HeaderCell { text: "ID"; widthRatio: 0.06 }
                        HeaderCell { text: "电表名称"; widthRatio: 0.16 }
                        HeaderCell { text: "报警类型"; widthRatio: 0.16 }
                        HeaderCell { text: "报警值"; widthRatio: 0.10 }
                        HeaderCell { text: "阈值"; widthRatio: 0.10 }
                        HeaderCell { text: "触发时间"; widthRatio: 0.18 }
                        HeaderCell { text: "状态"; widthRatio: 0.11 }
                        HeaderCell { text: "操作"; widthRatio: 0.08 }
                    }
                }

                // 数据列表
                ListView {
                    id: alarmListView
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    clip: true
                    model: alarmModel
                    spacing: 1

                    delegate: Rectangle {
                        width: alarmListView.width
                        height: 45
                        color: index % 2 === 0 ? "white" : "#fafafa"
                        border.color: "#f0f0f0"
                        border.width: 1

                        // 左侧指示条
                        Rectangle {
                            width: 3
                            height: parent.height
                            anchors.left: parent.left
                            color: {
                                if (model.acknowledged) return "#bdc3c7"
                                var typeStr = model.typeName || ""
                                if (typeStr.includes("电压") || typeStr.includes("Voltage"))
                                    return "#e74c3c"
                                if (typeStr.includes("电流") || typeStr.includes("Current"))
                                    return "#f39c12"
                                return "#95a5a6"
                            }
                        }

                        Row {
                            anchors.fill: parent
                            anchors.leftMargin: 10
                            anchors.rightMargin: 8
                            spacing: 0

                            // 选择框
                            Item {
                                width: parent.width * 0.05
                                height: parent.height
                                CheckBox {
                                    anchors.centerIn: parent
                                    checked: root.selectedAlarmIds.indexOf(model.alarmId) >= 0
                                    onCheckedChanged: {
                                        if (checked) {
                                            if (root.selectedAlarmIds.indexOf(model.alarmId) < 0) {
                                                root.selectedAlarmIds.push(model.alarmId)
                                                root.selectedAlarmIds = root.selectedAlarmIds
                                            }
                                        } else {
                                            var idx = root.selectedAlarmIds.indexOf(model.alarmId)
                                            if (idx >= 0) {
                                                root.selectedAlarmIds.splice(idx, 1)
                                                root.selectedAlarmIds = root.selectedAlarmIds
                                            }
                                        }
                                    }
                                }
                            }

                            DataCell { text: model.alarmId; widthRatio: 0.06 }
                            DataCell { text: model.meterName || ("电表-" + model.meterId); widthRatio: 0.16 }
                            DataCell { text: model.typeName; widthRatio: 0.16; textColor: model.acknowledged ? "#95a5a6" : "#e74c3c" }
                            DataCell { text: model.value.toFixed(1); widthRatio: 0.10 }
                            DataCell { text: model.threshold.toFixed(1); widthRatio: 0.10 }
                            DataCell { 
                                text: Qt.formatDateTime(model.timestamp, "MM-dd HH:mm:ss")
                                widthRatio: 0.18 
                            }

                            // 状态
                            Item {
                                width: parent.width * 0.11
                                height: parent.height

                                Rectangle {
                                    anchors.centerIn: parent
                                    width: 65
                                    height: 22
                                    radius: 11
                                    color: model.acknowledged ? "#d5f4e6" : "#ffe6e6"

                                    Text {
                                        anchors.centerIn: parent
                                        text: model.acknowledged ? "✓已确认" : "✗未确认"
                                        font.pixelSize: 9
                                        color: model.acknowledged ? "#27ae60" : "#e74c3c"
                                    }
                                }
                            }

                            // 操作
                            Item {
                                width: parent.width * 0.08
                                height: parent.height

                                Button {
                                    anchors.centerIn: parent
                                    text: model.acknowledged ? "详情" : "确认"
                                    font.pixelSize: 9
                                    implicitHeight: 22
                                    implicitWidth: 48
                                    enabled: !model.acknowledged
                                    onClicked: {
                                        if (!model.acknowledged) {
                                            acknowledgeAlarm(index)
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // 空状态提示
                    Label {
                        anchors.centerIn: parent
                        visible: alarmListView.count === 0
                        text: root.isQuerying ? "正在查询..." : "暂无报警记录\n请调整查询条件后重试"
                        font.pixelSize: 13
                        color: "#95a5a6"
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 分页控件（压缩到32px）
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 32
                    Layout.minimumHeight: 32
                    Layout.maximumHeight: 32
                    color: "#f5f7fa"
                    radius: 3

                    RowLayout {
                        anchors.fill: parent
                        anchors.margins: 5
                        spacing: 6

                        Text {
                            text: "每页 " + root.pageSize + " 条"
                            font.pixelSize: 10
                            color: "#7f8c8d"
                        }

                        Item { Layout.fillWidth: true }

                        Button {
                            text: "首页"
                            font.pixelSize: 10
                            padding: 4
                            implicitHeight: 26
                            enabled: root.currentPage > 1
                            onClicked: {
                                root.currentPage = 1
                                queryAlarms()
                            }
                        }

                        Button {
                            text: "上一页"
                            font.pixelSize: 10
                            padding: 4
                            implicitHeight: 26
                            enabled: root.currentPage > 1
                            onClicked: {
                                root.currentPage--
                                queryAlarms()
                            }
                        }

                        Text {
                            text: "第 " + root.currentPage + " / " + root.totalPages + " 页"
                            font.pixelSize: 10
                            color: "#2c3e50"
                        }

                        Button {
                            text: "下一页"
                            font.pixelSize: 10
                            padding: 4
                            implicitHeight: 26
                            enabled: root.currentPage < root.totalPages
                            onClicked: {
                                root.currentPage++
                                queryAlarms()
                            }
                        }

                        Button {
                            text: "末页"
                            font.pixelSize: 10
                            padding: 4
                            implicitHeight: 26
                            enabled: root.currentPage < root.totalPages
                            onClicked: {
                                root.currentPage = root.totalPages
                                queryAlarms()
                            }
                        }

                        Item { Layout.fillWidth: true }
                    }
                }
            }
        }
    }

    // CSV导出对话框
    FileDialog {
        id: saveDialog
        title: "导出报警记录"
        selectExisting: false
        nameFilters: ["CSV文件 (*.csv)"]
        defaultSuffix: "csv"
        folder: "file:///C:/Users/86188/Desktop"
        
        onAccepted: {
            var filePath = fileUrl.toString().replace("file:///", "")
            exportToCSV(filePath)
        }
    }

    // JavaScript函数

    // 查询报警记录
    function queryAlarms() {
        console.log("查询报警记录...")
        root.isQuerying = true
        root.selectedAlarmIds = []
        selectAllCheckbox.checked = false

        // 计算分页偏移量
        var offset = (root.currentPage - 1) * root.pageSize

        // 调用后端查询方法
        var startTimeStr = Qt.formatDateTime(root.startDate, Qt.ISODate)
        var endTimeStr = Qt.formatDateTime(root.endDate, Qt.ISODate)
        
        alarmModel.queryHistoryAlarms(
            root.selectedMeterId,
            startTimeStr,
            endTimeStr,
            root.acknowledgedFilter,
            offset,
            root.pageSize
        )

        // 更新统计信息
        root.statistics = alarmModel.getStatistics()
        
        // 计算总页数
        var totalCount = root.statistics.totalCount
        root.totalPages = Math.ceil(totalCount / root.pageSize)
        if (root.totalPages === 0) root.totalPages = 1

        root.isQuerying = false
        console.log("查询完成，共 " + totalCount + " 条记录")
    }

    // 确认单条报警
    function acknowledgeAlarm(index) {
        console.log("确认报警，索引: " + index)
        if (alarmModel.acknowledgeAlarmAt(index)) {
            console.log("报警确认成功")
            // 更新统计信息
            root.statistics = alarmModel.getStatistics()
        } else {
            console.error("报警确认失败")
        }
    }

    // 批量确认选中的报警
    function batchAcknowledge() {
        if (root.selectedAlarmIds.length === 0) {
            console.warn("未选择任何报警")
            return
        }

        console.log("批量确认报警，数量: " + root.selectedAlarmIds.length)
        var count = alarmModel.batchAcknowledgeByIds(root.selectedAlarmIds)
        console.log("成功确认 " + count + " 条报警")
        
        // 清空选中列表
        root.selectedAlarmIds = []
        selectAllCheckbox.checked = false
        
        // 更新统计信息
        root.statistics = alarmModel.getStatistics()
    }

    // 确认全部未确认报警
    function acknowledgeAll() {
        console.log("确认全部未确认报警")
        alarmModel.acknowledgeAllAlarms()
        
        // 清空选中列表
        root.selectedAlarmIds = []
        selectAllCheckbox.checked = false
        
        // 更新统计信息
        root.statistics = alarmModel.getStatistics()
    }

    // 全选报警
    function selectAllAlarms() {
        root.selectedAlarmIds = []
        for (var i = 0; i < alarmModel.count; ++i) {
            var alarm = alarmModel.getAlarmAt(i)
            if (alarm && alarm.alarmId) {
                root.selectedAlarmIds.push(alarm.alarmId)
            }
        }
        root.selectedAlarmIds = root.selectedAlarmIds // 触发更新
    }

    // 导出CSV
    function exportToCSV(filePath) {
        console.log("导出报警记录到: " + filePath)
        
        var startTimeStr = Qt.formatDateTime(root.startDate, Qt.ISODate)
        var endTimeStr = Qt.formatDateTime(root.endDate, Qt.ISODate)
        
        var success = alarmModel.exportToCSV(
            root.selectedMeterId,
            startTimeStr,
            endTimeStr,
            filePath
        )

        if (success) {
            console.log("导出成功")
            // 可以显示成功提示对话框
        } else {
            console.error("导出失败")
            // 可以显示错误提示对话框
        }
    }

    // 组件加载完成
    Component.onCompleted: {
        console.log("报警记录页面加载完成")
        // 初始查询
        queryAlarms()
    }

    // 内联组件定义
    component HeaderCell: Item {
        property string text: ""
        property real widthRatio: 0.1
        
        width: parent ? parent.width * widthRatio : 100
        height: parent ? parent.height : 30

        Text {
            anchors.centerIn: parent
            text: parent.text
            font.pixelSize: 9
            font.bold: true
            color: "#2c3e50"
        }
    }

    component DataCell: Item {
        property string text: ""
        property real widthRatio: 0.1
        property color textColor: "#2c3e50"
        
        width: parent ? parent.width * widthRatio : 100
        height: parent ? parent.height : 45

        Text {
            anchors.centerIn: parent
            text: parent.text
            font.pixelSize: 9
            color: parent.textColor
            elide: Text.ElideRight
            width: parent.width - 8
            horizontalAlignment: Text.AlignHCenter
        }
    }
}


